import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio, Table, Popconfirm, Pagination,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './List.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

/* eslint react/no-multi-comp:0 */
@connect(({ usr, opration, loading }) => ({
  usr,
  opration,
  loading: loading.effects['category/fetch'],
}))
@Form.create()
class ActiveCategory extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    formValues: {},
    updateValue: {},
    pageData: {
      size: 10,
      page: 1,
    },
    sortData: {
      order: 'createTime',
      direction: 'asc',
    },
  };
  columns = [
    {
      title: '序号',
      dataIndex: 'userId',
    },
    {
      title: '手机号',
      dataIndex: 'phoneNumber',
    },
    {
      title: '昵称',
      // dataIndex: 'status',
      dataIndex: 'name',
    },
    {
      title: '头像',
      // dataIndex: 'status',
      dataIndex: 'headPic',
      render: val => <span><img src={val} width="30px" height="30px" alt=""/></span>,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a, b) => Date.parse(a.createTime) > Date.parse(b.createTime),
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      sorter: (a, b) => Date.parse(a.updateTime) > Date.parse(b.updateTime),
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render: (text, item) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, item)}>修改</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    this.fetchMore(this.state.pageData.page, this.state.pageData.size);
    dispatch({
      type: 'opration/fetch',
      payload: {
        type: 'user',
      },
    });
    dispatch({
      type: 'usr/queryCount',
    });
  }

  fetchMore = (page, size) => {
    const { dispatch } = this.props;
    const { pageData, searchValues, sortData } = this.state;
    dispatch({
      type: 'usr/fetch',
      payload: { start: (page - 1) * 10, size: size, ...searchValues, ...sortData },
    });
  };
  cateogryDelete = (categoryId) => {
    this.props.dispatch({
      type: 'category/delete',
      payload: { type: 'activity', id: categoryId },
    });
  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    console.log('some data change');
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'category/fetch',
      payload: { type: 'activity' },
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;

    function dealObjectValue(obj) {
      var param = {};
      if (obj === null || obj === undefined || obj === '') return param;
      for (var key in obj) {
        if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
          param[key] = obj[key];
        }
      }
      return param;
    };
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        searchValues: dealObjectValue(values),
      });
      const { dispatch } = this.props;
      const { pageData, sortData } = this.state;
      dispatch({
        type: 'usr/fetch',
        payload: { start: 0, size: pageData.size, ...dealObjectValue(values), ...sortData },
      });
      dispatch({
        type: 'usr/queryCount',
        payload: { ...dealObjectValue(values) },
      });
    });
  };
  /*
    * 分页SizeChange
    * */
  onShowSizeChange = (current, pageSize) => {
    console.log(pageSize);
    this.setState({
      pageData: { page: 1, size: pageSize },
    });
    this.fetchMore(1, pageSize);
  };
  /*pageChange*/
  changePage = (page, pageSize) => {
    this.setState({
      pageData: { page: page, pageSize: this.state.pageData.size },
    });
    this.fetchMore(page, this.state.pageData.size);
  };
  handleModalVisible = (flag, item) => {
    this.setState({
      modalVisible: !!flag,
      updateValue: item || {},
    });
  };
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'usr/save',
      payload: fields,
    });
    this.handleModalVisible();
  };

  render() {
    const {
      form: { getFieldDecorator },
      usr: { list, countNum },
      opration,
      loading,
    } = this.props;
    const { selectedRows, modalVisible, pageData } = this.state;
    const parentMethods = {
      oprationList: opration.list,
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const mainSearch = (
      <Form layout="inline">
        <Row gutter={{ md: 6, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="phoneNumber">
              {getFieldDecorator('phoneNumber')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          {/*<Col md={6} sm={24}>*/}
          {/*<Form.Item label="开始时间">*/}
          {/*{getFieldDecorator('startCreateTime')(*/}
          {/*<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: "200px"}} placeholder="请输入活动开始时间"/>*/}
          {/*)}*/}
          {/*</Form.Item>*/}
          {/*</Col>*/}
          {/*<Col md={6} sm={24}>*/}
          {/*<Form.Item label="结束时间">*/}
          {/*{getFieldDecorator('endCreateTime')(*/}
          {/*<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: "200px"}} placeholder="请输入活动开始时间"/>*/}
          {/*)}*/}
          {/*</Form.Item>*/}
          {/*</Col>*/}
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button onClick={this.handleSearch} type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
    return (
      <PageHeaderWrapper title="类别列表" content={mainSearch}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/*<div className={styles.tableListForm}>{this.renderForm()}</div>*/}
            <div className={styles.tableListOperator}>
              <Button style={{ marginBottom: '20px' }} icon="plus" type="primary"
                      onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
            </div>
            <Table
              loading={loading}
              dataSource={list}
              pagination={false}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
            <Pagination style={{ 'marginTop': '30px' }} showSizeChanger onChange={this.changePage}
                        onShowSizeChange={this.onShowSizeChange} defaultPageSize={pageData.size}
                        defaultCurrent={pageData.page} total={countNum}/>
          </div>
        </Card>
        <CreateForm {...parentMethods} updateValue={this.state.updateValue} modalVisible={modalVisible}/>
      </PageHeaderWrapper>
    );
  }
}

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, updateValue, oprationList } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (updateValue && updateValue.userId) {
        handleAdd({ ...fieldsValue, userId: updateValue.userId });
      } else {
        handleAdd({ ...fieldsValue });
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      title={updateValue ? '编辑类别' : '新建类别'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="昵称">
        {form.getFieldDecorator('username', {
          initialValue: updateValue.name,
          rules: [{ required: true, message: '请输入至少二个字符！', min: 2 }],
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="手机号">
        {form.getFieldDecorator('phoneNumber', {
          initialValue: updateValue.phoneNumber,
          rules: [{ required: true, message: '手机号不能为空！'}],
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      {updateValue && <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="密码">
        {form.getFieldDecorator('password')(<Input placeholder="请输入"/>)}
      </FormItem>}
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图片">
        {form.getFieldDecorator('headPic', {
          initialValue: updateValue.headPic,
          rules: [{ required: true, message: '请选择用户图像', min: 2 }],
        })(<Select style={{ width: 200, height: 50 }}>
          {oprationList.map((item, index) => {
            return <Option key={index} value={item.pic} style={{ width: 200 }}>
              <div>
                <img src={item.pic} alt="" style={{ width: '40px' }}/>
              </div>
            </Option>;
          })}
        </Select>)}
      </FormItem>
    </Modal>
  );
});
export default ActiveCategory;
